package services

import (
	"errors"
	"fmt"
	"github.com/eyediy/dbcontrol"
	"crypto/md5"
	"encoding/hex"
	"github.com/lib/pq"
)

func transactionHandler(tx *dbcontrol.Tx, pErr *error) {
	if err := recover(); err != nil {
		rollbackErr := tx.Rollback()
		if rollbackErr != nil {
			*pErr = errors.New(fmt.Sprint("\n [rollbackErr] ", rollbackErr, "\n", err))
			return
		}
		*pErr = errors.New(fmt.Sprint("[transactionHandler] ", err))
		return
	}
	err := tx.Commit()
	if err != nil {
		if err, ok := err.(*pq.Error); ok {
			fmt.Println("pq error:", err.Code.Name())
		}
		*pErr = err
	}
}

func encPassword(pass string) string {
	h := md5.New()
	h.Write([]byte(fmt.Sprint(
		"黄鹤楼, 帽峰山, @2016-11-05 by harrse",
		pass,
		"salt_中国电信客服电话10086")))
	return hex.EncodeToString(h.Sum(nil))
}
